package com.lepu.app.fun.tool.ycqjs;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.MyArticleInfoActivity;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class YcqjsActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener, AsyncRequest {

    private String mCurrentDateString = "";
    private int mCurrentZq = 28;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedStatusBar = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index_ycqjs_activity);

        UtilityBase.setStatusBarRes(this, R.color.color_jqtx, true);
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
        finish(true);
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }


    /**
     * 初始化方法
     */
    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("预产期自测");
        topbar.setonTopbarNewLeftLayoutListener(this);
        topbar.setTopbarBackground(R.color.color_jqtx);

        TextView seeTefyTextView = (TextView) findViewById(R.id.seeTefyTextView);
        seeTefyTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        seeTefyTextView.getPaint().setAntiAlias(true);

        updateResult(false, null, null, null);

        TextView endTimeValueTextView = (TextView) findViewById(R.id.endTimeValueTextView);
        mCurrentDateString = DateUtilBase.stringFromDate(new Date(),
                DateUtilBase.YEAR_MONTH_DAY);
        endTimeValueTextView.setText(mCurrentDateString);
    }

    private void updateResult(boolean isResult, String result1, String result2, String result3) {
        TextView result1TextView = (TextView) findViewById(R.id.result1TextView);
        TextView result2TextView = (TextView) findViewById(R.id.result2TextView);
        TextView result3TextView = (TextView) findViewById(R.id.result3TextView);

        if (isResult) {
            result1TextView.setText(String.format("大概受孕时间：%s", result1));
            result2TextView.setText(String.format("预计出生时间：%s", result2));
            result3TextView.setText(String.format("宝宝当前月龄：%s", result3));

            //提交服务器
            Map<String, Object> map = new HashMap<String, Object>();
            JSONObject params = new JSONObject();
            try {
                params.put("DeviceID", Setting.DEVICEID);
                params.put("ApplicationID", Setting.APPLICATIONID);
                params.put("UserID", LoginUtil.getUserId());
                params.put("LoginToken", LoginUtil.getLoginToken());

                params.put("LastMenstruationDate", mCurrentDateString);
                params.put("MenstruationCycle", mCurrentZq);
//                params.put("", result1);
//                params.put("", result2);
//                params.put("", result3);

            } catch (Exception e) {
            }
            map.put("ht", params);

            showProgressDialog();
            ApiClient.http_post_main(Setting.getYcqzcUrl(), map, null, this,
                    "", true);
        } else {
            result1TextView.setText(String.format("大概受孕时间：待计算......"));
            result2TextView.setText(String.format("预计出生时间：待计算......"));
            result3TextView.setText(String.format("宝宝当前月龄：待计算......"));
        }
    }

    private void showZqSelect() {
        final ArrayList<Integer> dataArraylist = new ArrayList<Integer>();
        for (int i = 22; i <= 45; i++) {
            dataArraylist.add(i);
        }

        final String[] array = new String[dataArraylist.size()];
        int currentIndex = mCurrentZq - 22;

        for (int i = 0; i < dataArraylist.size(); i++) {
            array[i] = String.format("周期%d天", dataArraylist.get(i));
        }

        final MyDialog dialog = new MyDialog(this);
        dialog.setSimpleSelectPicker(array, currentIndex)
                .setTitle("请选择平均月经周期")
                .setNegativeButton(R.string.app_cancel,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        })
                .setPositiveButton(R.string.app_ok, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        WheelView wv_content = (WheelView) v
                                .findViewById(R.id.simpleSelectPicker);
                        int index = wv_content.getCurrentItem();

                        TextView zqValueTextView = (TextView) findViewById(R.id.zqValueTextView);
                        zqValueTextView.setText(String.valueOf(dataArraylist
                                .get(index))+"天");

                        mCurrentZq = dataArraylist.get(index);

                    }
                }).create(null).show();
    }

    private void showEndTimeSelect() {
        Date date = DateUtilBase.dateFromString(mCurrentDateString, DateUtilBase.YEAR_MONTH_DAY);

        new MyDialog(this)
                .setTitle("请选择末次月经时间")
                .setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
                .setNegativeButton(R.string.app_cancel,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        })
                .setPositiveButton(R.string.app_ok, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        // 如果是个数,则显示为"02"的样式
                        WheelView wv_year = (WheelView) v
                                .findViewById(R.id.year);
                        WheelView wv_month = (WheelView) v
                                .findViewById(R.id.month);
                        WheelView wv_day = (WheelView) v.findViewById(R.id.day);

                        String parten = "00";
                        DecimalFormat decimal = new DecimalFormat(parten);
                        // 设置日期的显示
                        String date = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
                                + "-"
                                + decimal.format((wv_month.getCurrentItem() + 1))
                                + "-"
                                + decimal.format((wv_day.getCurrentItem() + 1));


                        //末次月经时间可选范围：2015年1月1日~2020年12月31日，
                        // 当选择日期距当前日期超过超过280，toast提示：距离今天不能超过280天

                        Date selectDate = DateUtilBase.dateFromString(date,
                                DateUtilBase.YEAR_MONTH_DAY);
                        Date beginDate = DateUtilBase.dateFromString("2015-01-01",
                                DateUtilBase.YEAR_MONTH_DAY);
                        Date endDate = DateUtilBase.dateFromString("2020-12-31",
                                DateUtilBase.YEAR_MONTH_DAY);

                        long selectTime = selectDate.getTime();
                        long beginTime = beginDate.getTime();
                        long endTime = endDate.getTime();

                        if (selectTime < beginTime || selectTime > endTime) {
                            UIHelper.showToast(YcqjsActivity.this,
                                    "末次月经时间可选范围：2015年1月1日~2020年12月31日");
                            return;
                        }

                        long selectAddTime = DateUtilBase.addDateOfDay(selectDate, 280).getTime();
                        long systemTime = DateUtilBase.dateFromString(DateUtilBase.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY),
                                DateUtilBase.YEAR_MONTH_DAY).getTime();

                        if (selectAddTime - systemTime < 0) {
                            UIHelper.showToast(YcqjsActivity.this,
                                    "距离今天不能超过280天");
                            return;
                        }

                        mCurrentDateString = date;
                        TextView endTimeValueTextView = (TextView) findViewById(R.id.endTimeValueTextView);
                        endTimeValueTextView.setText(date);
                    }
                }).create(null).show();
    }

    /**
     * 受孕时间
     */
    private String computeResult1() {
        String result = "";

        int addDay = mCurrentZq - 14;
        Date date = DateUtilBase.dateFromString(mCurrentDateString, DateUtilBase.YEAR_MONTH_DAY);
        date = DateUtilBase.addDateOfDay(date, addDay);

        result = DateUtilBase.stringFromDate(date, DateUtilBase.YEAR_MONTH_DAY);
        return result;
    }

    /**
     * 出生时间
     */
    private String computeResult2() {
        String result = "";

        Date selectDate = DateUtilBase.dateFromString(mCurrentDateString, DateUtilBase.YEAR_MONTH_DAY);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(selectDate);

        int month = calendar.get(Calendar.MONTH)+1;
        Date date = null;
        if (month <= 3) {
            date = DateUtilBase.addDateOfMonth(selectDate, 9);
        } else {
            date = DateUtilBase.addDateOfMonth(selectDate, -3);
            date = DateUtilBase.addDateOfYear(date, 1);
        }
        date = DateUtilBase.addDateOfDay(date, mCurrentZq-22);

        result = DateUtilBase.stringFromDate(date, DateUtilBase.YEAR_MONTH_DAY);
        return result;
    }

    /**
     * 当前月龄
     */
    private String computeResult3() {
        String result = "";

        Date systemDate = DateUtilBase.dateFromString(DateUtilBase.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY),
                DateUtilBase.YEAR_MONTH_DAY);
        Date selectDate = DateUtilBase.dateFromString(mCurrentDateString, DateUtilBase.YEAR_MONTH_DAY);
        long systemTime = systemDate.getTime();
        long selectTime = selectDate.getTime();

        if(selectTime < systemTime)
        {
            //加1天
            int days = (int) ((systemTime-selectTime+(1*1000 * 60 * 60 * 24) ) / (1000 * 60 * 60 * 24));

            int weekValue = days /  7;
            int dayValue = days % 7;

            if(dayValue > 0)
            {
                result = String.format("%d周，%d天",weekValue,dayValue);
            }else{
                result = String.format("%d周",weekValue);
            }

        }else{
            result = "宝宝还未出生";
        }

        return result;
    }

    public void viewClick(View view) {
        int rid = view.getId();
        switch (rid) {
            case R.id.zqValueTextView:

                showZqSelect();
                break;
            case R.id.endTimeValueTextView:

                showEndTimeSelect();
                break;
            case R.id.finishButton:

                String result1 = computeResult1();
                String result2 = computeResult2();
                String result3 = computeResult3();

                updateResult(true, result1, result2, result3);
                break;
            case R.id.seeTefyTextView:
                //链接到胎儿发育文章列表
//                String articleID = "252";
//                if(!Setting.DEBUG)
//                {
//                    articleID = "1731";
//                }
//                String url = Setting.getShareMyArticleInfoUrl(this,articleID);
//
//                Intent intent = new Intent(this, AppBroswerActivity.class);
//                intent.putExtra("title","宝宝宫内成长记");
//                intent.putExtra("url", url);
//                startActivity(intent, true);

//                MyNetUtil.getInstance().requestArticleDetail(
//                        this, articleID,
//                        "", "", "宝宝宫内成长记");

                String url = Setting.getBaoBaoGrowUrl(this);
                Intent intent = new Intent(this,
                        MyArticleInfoActivity.class);

                //只有系列文章需要
                intent.putExtra("ArticleTag", "宝宝宫内成长记");

                intent.putExtra("url", url);
                intent.putExtra("TargetID", "");
                startActivity(intent, true);
                break;
            default:
                break;
        }
    }

    @Override
    public void RequestComplete(Object o, Object o1) {
        LogUtilBase.LogD(null, "预产期自测数据提交成功");
        hideProgressDialog();
    }

    @Override
    public void RequestError(Object o, int i, String s) {
        LogUtilBase.LogD(null, "预产期自测数据提交失败");
        hideProgressDialog();
    }
}
